<template>
  <div class="residency-application">
    <h1>桂林电子科技大学科技园</h1>
    <h2>入 园 申 请 表 (新成立企业)</h2>

    <!-- 状态显示 -->
    <div v-if="form.status !== undefined" class="status-display">
      <el-tag :type="getStatusType(form.status)" size="large" effect="dark">
        {{ getStatusText(form.status) }}
      </el-tag>
    </div>

    <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="150px" style="max-width: 1200px; width: 100%"
      :disabled="mode === 'view' || (form.status !== undefined && form.status === 1)">
      <!-- 企业基本信息 -->
      <el-card>
        <div slot="header" class="header">企业基本信息</div>
        <el-form-item label="申请时间" prop="applyDate">
          <el-date-picker v-model="form.applyDate" type="date" placeholder="请选择申请日期"
            value-format="YYYY-MM-DDTHH:mm:ss.SSSZ" style="width: 100%" />
        </el-form-item>
        <el-form-item label="新设立企业名称" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="企业负责人" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入企业负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入负责人联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱地址" prop="contactEmail">
              <el-input v-model="form.contactEmail" placeholder="请输入负责人邮箱地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="经办人" prop="agentName">
              <el-input v-model="form.agentName" placeholder="请输入经办人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="agentPhone">
              <el-input v-model="form.agentPhone" placeholder="请输入经办人联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱地址" prop="agentEmail">
              <el-input v-model="form.agentEmail" placeholder="请输入经办人邮箱地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="拟注册资本(万元)" prop="registerMoney">
              <el-input v-model="form.registerMoney" suffix="万元" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际募集资金(万元)" prop="raisedMoney">
              <el-input v-model="form.raisedMoney" suffix="万元" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="初始员工人数" prop="initialEmployees">
              <el-input v-model="form.initialEmployees" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预计注册日期" prop="expectedRegisterDate">
              <el-date-picker v-model="form.expectedRegisterDate" type="date" placeholder="请选择日期"
                value-format="YYYY-MM-DDTHH:mm:ss.SSSZ" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="拟注册企业性质" prop="region">
          <el-select v-model="form.region" placeholder="请选择你的企业资质">
            <el-option label="大学生创业企业" value="大学生创业企业" />
            <el-option label="高校教师创业企业" value="高校教师创业企业" />
            <el-option label="民营企业" value="民营企业" />
            <el-option label="外资企业" value="外资企业" />
            <el-option label="股份制企业" value="股份制企业" />
            <el-option label="国有及国有控股企业" value="国有及国有控股企业" />
            <el-option label="其他企业" value="其他企业" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属行业" prop="industry">
          <el-radio-group v-model="form.industry">
            <el-radio label="电子信息产业" value="电子信息产业">电子信息产业</el-radio>
            <el-radio label="生物医学产业" value="生物医学产业">生物医学产业</el-radio>
            <el-radio label="新能源产业" value="新能源产业">新能源产业</el-radio>
            <el-radio label="新材料产业" value="新材料产业">新材料产业</el-radio>
            <el-radio label="先进制造产业" value="先进制造产业">先进制造产业</el-radio>
            <el-radio label="环保节能减排" value="环保节能减排">环保节能减排</el-radio>
            <el-radio label="高技术服务业" value="高技术服务业">高技术服务业</el-radio>
            <el-radio label="软件外包服务业" value="软件外包服务业">软件外包服务业</el-radio>
            <el-radio label="其他" value="其他">
              其他
              <el-input v-if="form.industry === '其他'" v-model="form.otherIndustry" placeholder="请填写其他行业"
                style="margin-left: 10px; width: 200px" />
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="主营业务" prop="mainBusiness">
          <el-input v-model="form.mainBusiness" placeholder="请填写主营业务" />
        </el-form-item>
        <el-form-item label="入园业务" prop="businessType">
          <el-checkbox-group v-model="form.businessType">
            <el-checkbox label="研究" value="研究">研究</el-checkbox>
            <el-checkbox label="开发" value="开发">开发</el-checkbox>
            <el-checkbox label="生产" value="生产">生产</el-checkbox>
            <el-checkbox label="销售" value="销售">销售</el-checkbox>
            <el-checkbox label="服务" value="服务">服务</el-checkbox>
            <el-checkbox label="其他" value="其他">
              其他
              <el-input v-if="form.businessType.includes('其他')" v-model="form.otherBusinessType" placeholder="请填写其他业务"
                style="margin-left: 10px; width: 200px" />
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-card>

      <!-- 园区场地租赁需求 -->
      <el-card>
        <div slot="header" class="header">园区场地租赁需求</div>
        <el-form-item label-width="0">
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="租赁面积" prop="rentalArea">
                <el-input type="text" v-model="form.rentalArea">
                  <template #suffix>平方米</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="租期" prop="rentalPeriod">
                <el-input type="text" v-model="form.rentalPeriod">
                  <template #suffix>年</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="位置要求" prop="locationRequirement">
          <el-input type="textarea" v-model="form.locationRequirement" placeholder="请输入位置要求" />
        </el-form-item>
        <el-form-item label="其他要求">
          <el-input type="textarea" v-model="form.otherRequirement" placeholder="请输入其他要求" />
        </el-form-item>
      </el-card>

      <!-- 股东构成 -->
      <el-card>
        <div slot="header" class="header">股东构成</div>
        <el-form-item label-width="0" prop="shareholders">
          <el-table :data="form.shareholders" style="width: 100%">
            <el-table-column label="序号" type="index" width="60" />
            <el-table-column prop="name" label="股东姓名或名称">
              <template #default="scope">
                <el-form-item :prop="'shareholders.' + scope.$index + '.name'"
                  :rules="[{ required: true, message: '请输入股东姓名', trigger: 'blur' }]">
                  <el-input v-model="scope.row.name" placeholder="股东名称" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="ratio" label="股份比例">
              <template #default="scope">
                <el-form-item :prop="'shareholders.' + scope.$index + '.ratio'"
                  :rules="[{ required: true, message: '请输入股份比例', trigger: 'blur' }]">
                  <el-input v-model="scope.row.ratio" placeholder="股份比例" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="nature" label="股东性质">
              <template #default="scope">
                <el-form-item :prop="'shareholders.' + scope.$index + '.nature'"
                  :rules="[{ required: true, message: '请输入股东性质', trigger: 'blur' }]">
                  <el-input v-model="scope.row.nature" placeholder="股东性质" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button type="danger" @click="removeShareholder(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="addShareholder">增加股东</el-button>
        </el-form-item>
      </el-card>

      <!-- 主要人员简介 -->
      <el-card>
        <div slot="header" class="header">主要人员简介</div>
        <el-form-item label-width="0" prop="members">
          <el-table :data="form.members" style="width: 100%">
            <el-table-column label="序号" type="index" width="60" />
            <el-table-column prop="name" label="姓名">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.name'"
                  :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]">
                  <el-input v-model="scope.row.name" placeholder="人员姓名" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="birthDate" label="出生年月">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.birthDate'"
                  :rules="[{ required: true, message: '请选择出生年月', trigger: 'change' }]">
                  <el-date-picker v-model="scope.row.birthDate" type="date" placeholder="选择日期"
                    value-format="YYYY-MM-DDTHH:mm:ss.SSSZ" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="job" label="职务">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.job'"
                  :rules="[{ required: true, message: '请输入职务', trigger: 'blur' }]">
                  <el-input v-model="scope.row.job" placeholder="职务" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="school" label="毕业院校">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.school'"
                  :rules="[{ required: true, message: '请输入毕业院校', trigger: 'blur' }]">
                  <el-input v-model="scope.row.school" placeholder="毕业院校" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="职称">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.title'"
                  :rules="[{ required: true, message: '请输入职称', trigger: 'blur' }]">
                  <el-input v-model="scope.row.title" placeholder="职称" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="education" label="学历">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.education'"
                  :rules="[{ required: true, message: '请输入学历', trigger: 'blur' }]">
                  <el-input v-model="scope.row.education" placeholder="学历" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="major" label="专业">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.major'"
                  :rules="[{ required: true, message: '请输入专业', trigger: 'blur' }]">
                  <el-input v-model="scope.row.major" placeholder="专业" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button type="danger" @click="removeMember(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="addMember">增加成员</el-button>
        </el-form-item>
      </el-card>

      <!-- 入园项目简要介绍和分析 -->
      <el-card>
        <div slot="header" class="header">入园项目简要介绍和分析</div>
        <el-form-item label="项目简介" prop="projectIntroduction">
          <el-input v-model="form.projectIntroduction" type="textarea" placeholder="请输入项目的概述，包括目标、范围和主要特点等" />
        </el-form-item>
        <el-form-item label="竞争优势分析" prop="competitiveAdvantage">
          <el-input v-model="form.competitiveAdvantage" type="textarea" placeholder="请描述该项目相较于竞争对手的优势所在" />
        </el-form-item>
        <el-form-item label="市场前景分析" prop="marketProspects">
          <el-input v-model="form.marketProspects" type="textarea" placeholder="请分析该项目在当前市场环境下的发展潜力及预期增长趋势" />
        </el-form-item>
        <el-form-item label="能耗情况" prop="energyConsumption">
          <el-input v-model="form.energyConsumption" type="textarea" placeholder="请详细描述项目预计的能源消耗量及其对环境的影响" />
        </el-form-item>
        <el-form-item label="污染情况" prop="pollution">
          <el-input v-model="form.pollution" type="textarea" placeholder="请说明项目可能产生的污染物种类及其处理措施" />
        </el-form-item>
        <el-form-item label="噪声情况" prop="noise">
          <el-input v-model="form.noise" type="textarea" placeholder="请描述项目运行过程中可能产生的噪音水平及其控制方案" />
        </el-form-item>
        <el-form-item label="其他情况">
          <el-input v-model="form.otherConditions" type="textarea" placeholder="请提供上述未涵盖但与项目相关的其他重要信息" />
        </el-form-item>
      </el-card>

      <!-- 文件上传 -->
      <el-card>
        <div slot="header" class="header">上传文件</div>
        <el-form-item label="教师资格证" prop="teacherCertificate">
          <el-upload class="upload-demo" :http-request="handleSuccess" :on-error="handleError"
            :before-upload="beforeUpload" name="teacherCertificate">
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="学生证" prop="studentCertificate">
          <el-upload class="upload-demo" :http-request="handleSuccess" :on-error="handleError"
            :before-upload="beforeUpload" name="studentCertificate">
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="校友毕业证或学位证" prop="graduationCertificate">
          <el-upload class="upload-demo" :http-request="handleSuccess" :on-error="handleError"
            :before-upload="beforeUpload" name="graduationCertificate">
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-card>

      <el-form-item label="科技园意见">
        <el-input disabled type="textarea" placeholder="等待领导填写意见" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item>
        <el-button v-if="mode !== 'view' && form.status !== 1" type="primary" @click="submitForm">提交</el-button>
        <el-button v-if="mode !== 'view' && form.status !== 1" @click="saveDraft">保存草稿</el-button>
        <el-button v-if="mode !== 'view' && form.status === 1" type="warning"
          @click="withdrawApplication">撤回申请</el-button>
        <el-button v-if="mode !== 'view' && form.status === 1" type="danger" @click="deleteApplication">删除申请</el-button>
        <el-button v-if="mode !== 'view'" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <!--    提交后才能打印  打印到我的申请列表中可以查看  -->
    <!--    <div style="text-align: center; margin-top: 20px;">-->
    <!--      <el-button type="primary" @click="printForm">打印</el-button>-->
    <!--    </div>-->
    <span>注：请同时提供负责人身份证复印件。</span>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { NewEnterpriseApplication, getEnterpriseApplicationDetail, editEnterpriseApplication, delEnterpriseApplication } from '@/api/enterpeise';
import { uploadFile } from '@/api/file';
import type { ResidencyApplication, EnterpriseMember } from '@/types/type';
import type { ComponentSize, FormInstance, FormRules, UploadRequestOptions } from 'element-plus';
import type { AjaxResult } from '@/types/resultTypes';
import FileUpload from '../../components/fileUpload.vue';


const route = useRoute();
const router = useRouter();
const ruleFormRef = ref<FormInstance>();

// 表单验证规则
const rules = reactive<FormRules>({
  applyDate: [{ required: true, message: '请选择申请日期', trigger: 'change' }],
  itemName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  contactName: [{ required: true, message: '请输入企业负责人', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入负责人联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入负责人邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  agentName: [{ required: true, message: '请输入经办人', trigger: 'blur' }],
  agentPhone: [
    { required: true, message: '请输入经办人联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  agentEmail: [
    { required: true, message: '请输入经办人邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  registerMoney: [
    { required: true, message: '请输入拟注册资本', trigger: 'blur' },
    { pattern: /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/, message: '请输入正确资本(两位小数)', trigger: 'blur' }
  ],
  raisedMoney: [
    { required: true, message: '请输入实际募集资金', trigger: 'blur' },
    { pattern: /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/, message: '请输入正确资金(两位小数)', trigger: 'blur' }
  ],
  initialEmployees: [
    { required: true, message: '请输入初始员工人数', trigger: 'blur' },
    { pattern: /^[1-9]\d{0,9}$/, message: '请输入正确的初始员工人数', trigger: 'blur' }
  ],
  expectedRegisterDate: [{ required: true, message: '请选择预计注册日期', trigger: 'change' }],
  region: [{ required: true, message: '请选择企业性质', trigger: 'change' }],
  industry: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
  mainBusiness: [{ required: true, message: '请输入主营业务', trigger: 'blur' }],
  businessType: [{ required: true, message: '请选择入园业务', trigger: 'change' }],
  rentalArea: [
    { required: true, message: '请输入租赁面积', trigger: 'blur' },
    { pattern: /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/, message: '请输入正确面积(两位小数)', trigger: 'blur' }
  ],
  rentalPeriod: [
    { required: true, message: '请输入租期', trigger: 'blur' },
    { pattern: /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/, message: '请输入正确租期(两位小数)', trigger: 'blur' }
  ],
  locationRequirement: [{ required: true, message: '请输入位置要求', trigger: 'blur' }],
  projectIntroduction: [{ required: true, message: '请输入项目简介', trigger: 'blur' }],
  competitiveAdvantage: [{ required: true, message: '请输入竞争优势分析', trigger: 'blur' }],
  marketProspects: [{ required: true, message: '请输入市场前景分析', trigger: 'blur' }],
  energyConsumption: [{ required: true, message: '请输入能耗情况', trigger: 'blur' }],
  pollution: [{ required: true, message: '请输入污染情况', trigger: 'blur' }],
  noise: [{ required: true, message: '请输入噪声情况', trigger: 'blur' }],
  shareholders: [{
    type: 'array',
    required: true,
    message: '请至少添加一个股东信息',
    trigger: 'change'
  }],
  members: [{
    type: 'array',
    required: true,
    message: '请至少添加一个主要人员信息',
    trigger: 'change'
  }]
});

// 扩展ResidencyApplication类型，添加状态和ID字段
interface ExtendedResidencyApplication extends ResidencyApplication {
  status?: number; // 0-保存草稿，1-已提交，2-审核中，3-已完成
  id?: number; // ID字段用于编辑
  teacherCertificate?: string;
  studentCertificate?: string;
  graduationCertificate?: string;
}

const form = ref<ExtendedResidencyApplication>(
  JSON.parse(
    // localStorage.getItem('ResidencyApplicationForm') ||
    JSON.stringify({
      name: '',
      applyDate: '',
      itemName: '',
      numbers: 0,
      contactName: '',
      contactPhone: '',
      contactEmail: '',
      agentName: '',
      agentPhone: '',
      agentEmail: '',
      registerMoney: 0,
      raisedMoney: 0,
      initialEmployees: 0,
      expectedRegisterDate: '',
      region: '',
      shareholdingRatio: '',
      isQualified: false,
      businessScope: '',
      members: [{
        name: '',
        birthDate: '',
        job: '',
        school: '',
        title: '',
        education: '',
        major: '',
      }],
      shareholders: [{
        name: '',
        ratio: '',
        nature: '',
      }],
      projectIntroduction: '',
      competitiveAdvantage: '',
      marketProspects: '',
      energyConsumption: '',
      pollution: '',
      noise: '',
      otherConditions: '',
      teacherOpinion: '',
      collegeOpinion: '',
      officeOpinion: '',
      leaderOpinion: '',
      industry: '',
      otherIndustry: '',
      mainBusiness: '',
      businessType: [],
      otherBusinessType: '',
      rentalArea: '',
      locationRequirement: '',
      rentalPeriod: '',
      otherRequirement: '',
      remarks: '',
      status: 0, // 默认为草稿状态
      id: undefined,
    })
  )
);

// 获取模式（查看/编辑）
const mode = ref(route.query.mode as string || 'edit');

// 添加状态管理变量
const totalRecord = ref(0); // 用来标记用户是不是第一次提交 0，1表示是从我的申请中点击编辑过来的

// 加载现有数据
const loadExistingData = async (id: string) => {
  try {
    const bigIntId = BigInt(id);
    const res = await getEnterpriseApplicationDetail(bigIntId) as unknown as AjaxResult<any>;

    if (res.code === 200) {
      // 填充表单数据
      form.value = res.data;
      totalRecord.value = 1; // 标记为编辑模式
      ElMessage.success('数据加载成功');
    } else {
      ElMessage.error(res.msg || '数据加载失败');
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('数据加载失败');
  }
};

// 组件挂载时加载数据
onMounted(() => {
  // 从路由参数获取
  const id = route.query.id;
  if (id) {
    loadExistingData(id.toString());
  }
});


// 增加股东
const addShareholder = () => {
  ruleFormRef.value?.clearValidate('shareholders');
  form.value.shareholders.push({
    name: '',
    ratio: '',
    nature: '',
  });
};

// 删除股东
const removeShareholder = (index: number) => {
  form.value.shareholders.splice(index, 1);
};

// 监听表单数据变化并保存到 localStorage
watch(
  form,
  (newForm) => {
    localStorage.setItem('ResidencyApplicationForm', JSON.stringify(newForm));
  },
  { deep: true }
);

// 增加成员
const addMember = () => {
  ruleFormRef.value?.clearValidate('members');
  form.value.members.push({
    name: '',
    birthDate: '',
    job: '',
    school: '',
    title: '',
    education: '',
    major: '',
  });
};

// 删除成员
const removeMember = (index: number) => {
  form.value.members.splice(index, 1);
};

// 上传相关方法
const handleSuccess = async (options: UploadRequestOptions) => {
  const formData = new FormData();
  formData.append('file', options.file);
  try {
    const result = await uploadFile(formData);
    console.log(result)
    if (result.code === 200) {
      ElMessage.success('上传成功');
      // 根据上传的文件类型设置对应的字段
      const fileType = options.data?.name as string;
      if (fileType === 'teacherCertificate') {
        form.value.teacherCertificate = result.data;
      } else if (fileType === 'studentCertificate') {
        form.value.studentCertificate = result.data;
      } else if (fileType === 'graduationCertificate') {
        form.value.graduationCertificate = result.data;
      }
    } else {
      ElMessage.error(result.msg || '上传失败');
    }
  } catch (error) {
    ElMessage.error('上传失败');
  }
};

const handleError = () => {
  ElMessage.error('上传失败');
};

const beforeUpload = (file: File) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB!');
  }
  return isLt2M;
};

// 提交表单
const submitForm = async () => {
  console.log('点击')
  if (!ruleFormRef.value) return;

  await ruleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      console.log('表单验证通过')
      try {
        // 设置状态为已提交
        form.value.status = 1;

        const api = totalRecord.value === 1 ? editEnterpriseApplication : NewEnterpriseApplication;
        const res = await api(form.value) as unknown as AjaxResult<any>;
        if (res.code === 200) {
          ElMessage.success(totalRecord.value === 1 ? '更新成功' : '提交成功');
          localStorage.removeItem('ResidencyApplicationForm'); // 提交成功后清除本地存储
          // 跳转到我的申请列表
          router.push('/personal-center/enterprise-settlement/my-application');
        } else {
          ElMessage.error(res.msg || '提交失败');
        }
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
      }
    } else {
      ElMessage.error('表单验证不通过')
      console.log('表单验证不通过')
    }
  });
};

// 保存草稿
const saveDraft = async () => {
  try {
    // 设置状态为草稿
    form.value.status = 0;

    const api = totalRecord.value === 1 ? editEnterpriseApplication : NewEnterpriseApplication;
    const res = await api(form.value) as unknown as AjaxResult<any>;

    if (res.code === 200) {
      ElMessage.success('草稿保存成功');
      localStorage.removeItem('ResidencyApplicationForm'); // 保存成功后清除本地存储
      // 跳转到我的申请列表
      router.push('/personal-center/enterprise-settlement/my-application');
    } else {
      ElMessage.error(res.msg || '保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败');
  }
};

// 重置表单
const resetForm = () => {
  ruleFormRef.value?.resetFields();
  form.value.otherRequirement = ''
  form.value.otherConditions = ''
  form.value.remarks = ''
  localStorage.removeItem('ResidencyApplicationForm'); // 重置表单时清除本地存储
};


// 撤回申请
const withdrawApplication = async () => {
  try {
    if (!form.value.id) {
      ElMessage.error('申请ID不存在');
      return;
    }

    // 设置状态为草稿
    form.value.status = 0;

    const res = await editEnterpriseApplication(form.value) as unknown as AjaxResult<any>;
    if (res.code === 200) {
      ElMessage.success('撤回成功');
      // 跳转到我的申请列表
      router.push('/personal-center/enterprise-settlement/my-application');
    } else {
      ElMessage.error(res.msg || '撤回失败');
    }
  } catch (error) {
    console.error('撤回失败:', error);
    ElMessage.error('撤回失败');
  }
};

// 删除申请
const deleteApplication = async () => {
  try {
    if (!form.value.id) {
      ElMessage.error('申请ID不存在');
      return;
    }

    const res = await delEnterpriseApplication(form.value.id.toString()) as unknown as AjaxResult<any>;
    if (res.code === 200) {
      ElMessage.success('删除成功');
      // 跳转到我的申请列表
      router.push('/personal-center/enterprise-settlement/my-application');
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败');
  }
};

// 获取状态类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'info'; // 草稿
    case 1:
      return 'warning'; // 已提交
    case 2:
      return 'primary'; // 审核中
    case 3:
      return 'success'; // 已完成
    default:
      return 'info';
  }
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '草稿';
    case 1:
      return '已提交';
    case 2:
      return '审核中';
    case 3:
      return '已完成';
    default:
      return '未知状态';
  }
};
</script>

<style lang="scss" scoped>
.header {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 20px;
}

.el-card {
  margin: 20px auto;
}

.residency-application {
  width: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-weight: bold;

  :deep(.el-form-item__label) {
    font-weight: bold;
  }

  :deep(.el-table th, .el-table td) {
    font-weight: bold;
  }
}

.status-display {
  margin: 20px 0;
  text-align: center;

  .el-tag {
    font-size: 16px;
    padding: 8px 16px;
  }
}
</style>
